﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;

namespace SVNMultiWacher
{
    public partial class Service1 : ServiceBase
    {
        FileSystemWatcher myWatcher = null;
        string LocalPhysicsPath = "";
        string BatPath = "";
        string LogFile = "";

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                LocalPhysicsPath = ConfigurationManager.AppSettings["LocalPhysicsPath"];
                BatPath = ConfigurationManager.AppSettings["BatPath"];
                if (!BatPath.EndsWith(@"\")) BatPath += @"\";
                LogFile = ConfigurationManager.AppSettings["LogFile"].Replace("%Y", DateTime.Now.Year.ToString()).Replace("%M", DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString()).Replace("%D", DateTime.Now.Day.ToString().Length == 1 ? "0" + DateTime.Now.Day.ToString() : DateTime.Now.Day.ToString());
            }
            catch (Exception ex)
            {
                outTxt(ex.Message);
            }

            outTxt("服务已启动");

            if (!Directory.Exists(LocalPhysicsPath))
            {
                outTxt(LocalPhysicsPath + "不存在");
                return;
            }

            try
            {
                myWatcher = new FileSystemWatcher();
                myWatcher.Path = LocalPhysicsPath;
                myWatcher.IncludeSubdirectories = true;
                myWatcher.Filter = "current";
                myWatcher.NotifyFilter = myWatcher.NotifyFilter | NotifyFilters.LastWrite;

                myWatcher.Changed += new FileSystemEventHandler(OnChanged);
                myWatcher.Created += new FileSystemEventHandler(OnChanged);
                myWatcher.Deleted += new FileSystemEventHandler(OnChanged);
                myWatcher.Renamed += new RenamedEventHandler(Renamed);

                myWatcher.EnableRaisingEvents = true;
                outTxt("监控已启动");
            }
            catch (Exception ex)
            {
                outTxt(ex.Message);
            }
        }

        protected override void OnStop()
        {
            myWatcher.EnableRaisingEvents = false;
            outTxt("监控已停止");
            outTxt("服务已停止");
        }

        protected void OnChanged(object source, FileSystemEventArgs e)
        {
            ReposSync(e.FullPath);
        }

        protected void Renamed(object source, RenamedEventArgs e)
        {
            ReposSync(e.FullPath);
        }

        protected void ReposSync(string filePath)
        {
            try
            {
                string batFile = filePath.Replace(LocalPhysicsPath, "").Replace(@"db\current", "").Replace(@"\", "") + @".bat";
                outTxt("更新" + filePath + ",执行" + BatPath + batFile);
                exec(BatPath + batFile);
            }
            catch (Exception ex)
            {
                outTxt(ex.Message);
            }
        }

        protected void outTxt(string txt)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
                StreamWriter text = new StreamWriter(fs);
                text.WriteLine(DateTime.Now.ToString() + ":" + txt);
                text.Flush();
            }
            catch (Exception ex)
            {
                fs = new FileStream(@"c:\error.log", FileMode.Append, FileAccess.Write, FileShare.Read);
                StreamWriter text = new StreamWriter(fs);
                text.WriteLine(DateTime.Now.ToString() + ":" + ex.Message);
                text.Flush();
            }
            finally
            {
                if (fs != null) fs.Dispose();
            }
        }

        protected void exec(string path)
        {
            if (!File.Exists(path)) return;

            try
            {
                System.Diagnostics.Process cmd = new System.Diagnostics.Process();
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.FileName = path;
                cmd.StartInfo.Arguments = "";
                cmd.StartInfo.UseShellExecute = false;
                cmd.Start();
                string Result = cmd.StandardOutput.ReadToEnd();
                outTxt(Result);
                cmd.WaitForExit();
            }
            catch (Exception ex)
            {
                outTxt(ex.Message);
            }
        }
    }
}
